package com.fas.system.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fas.common.constant.Constants;
import com.fas.common.core.redis.RedisCache;
import com.fas.system.domain.SysArea;
import com.fas.system.mapper.SysAreaMapper;
import com.fas.system.service.ISysAreaService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysAreaServiceImpl implements ISysAreaService {

    @Resource
    private SysAreaMapper sysAreaMapper;
    @Resource
    private RedisCache redisCache;

    /**
     * 初始化数据至redis数据库
     */
    @PostConstruct
    public void init(){
        redisCache.setCacheObject(Constants.SYS_AREA_KEY, sysAreaMapper.findLikeEquipmentArea());
    }

    private List<Tree<String>> convertTree(List<SysArea> list){
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的
        treeNodeConfig.setWeightKey("level");
        treeNodeConfig.setIdKey("code");
        treeNodeConfig.setParentIdKey("parentCode");
        treeNodeConfig.setNameKey("name");
        treeNodeConfig.setChildrenKey("children");
        // 最大递归深度
        treeNodeConfig.setDeep(3);
        //转换器
        List<Tree<String>> treeList = TreeUtil.build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(String.valueOf(treeNode.getCode()));
                    tree.setParentId(String.valueOf(treeNode.getParentCode()));
                    tree.setWeight(treeNode.getLevel());
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("telephoneCode", treeNode.getTelephoneCode());
                    tree.putExtra("nameFirstChar", treeNode.getNameFirstChar());
                    tree.putExtra("center", treeNode.getCenter());
                    tree.putExtra("longitude", treeNode.getLongitude());
                    tree.putExtra("latitude", treeNode.getLatitude());
                    tree.putExtra("id", treeNode.getId());
                });
        return treeList;
    }

    @Override
    public List<Tree<String>> findLikeEquipmentArea() {
        List<SysArea> list = redisCache.getCacheObject(Constants.SYS_AREA_KEY);
        if (CollectionUtils.isEmpty(list)){
            this.init();
        }
        return convertTree(list);
    }

    /**
     * 临时只用一次
     * @return
     */
    @Override
    public List<Tree<String>> insert() {
        InputStream inputStream = this.getClass().getResourceAsStream("/area.json");
        Reader reader = null;
        try {
            reader = new InputStreamReader(inputStream, "Utf-8");

            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            String jsonStr = sb.toString();

            JSONObject msgEncap = JSON.parseObject(jsonStr);
            JSONArray arr = msgEncap.getJSONArray("data");

            List<SysArea> sysAreas = new ArrayList<>(arr.size());
            for (int i = 0; i < arr.size(); i++) {
                JSONObject jsonObject1 = arr.getJSONObject(i);
                sysAreas.add(JSON.parseObject(JSON.toJSONString(jsonObject1), SysArea.class));
                JSONArray jsonArray = arr.getJSONObject(i).getJSONArray("children");     //各个市
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject jsonObject2 = jsonArray.getJSONObject(j);
                    sysAreas.add(JSON.parseObject(JSON.toJSONString(jsonObject2), SysArea.class));
                    // 各个县
                    JSONArray jsonArray2 = jsonArray.getJSONObject(j).getJSONArray("children");
                    for (int k = 0; k < jsonArray2.size(); k++) {
                        JSONObject jsonObject3 = jsonArray2.getJSONObject(k);
                        sysAreas.add(JSON.parseObject(JSON.toJSONString(jsonObject3), SysArea.class));
                    }
                }
            }
            System.err.println("sysAreas 大小："+sysAreas.size());

//            for (SysArea sysArea : sysAreas) {
//                sysAreaMapper.insert(sysArea);
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 临时只用一次，将县数据缓存至数据库
     */

    @Override
    public void insert_x() {
        FileReader f = null;
        BufferedReader b = null;
        try {
            List<String> arrayList = new ArrayList<>();

            f = new FileReader(new File("D:\\temp\\error3.txt"));
            b = new BufferedReader(f);
            String s;
            //判断是否到一行字符串
            while ((s = b.readLine()) != null) {
                arrayList.add(s);
            }
            for (String s1 : arrayList) {
                JSONObject jsonObject = JSON.parseObject(s1);
                JSONArray data = jsonObject.getJSONArray("data");
                for (int i = 0; i < data.size(); i++) {
                    JSONObject jsonObject1 = data.getJSONObject(i);

                    SysArea sysArea = JSON.parseObject(JSON.toJSONString(jsonObject1), SysArea.class);
                    System.out.println("sysArea : " + sysArea);
                    sysAreaMapper.insert(sysArea);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                b.close();
                f.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<SysArea> findNameByParentCode(String parentCode) {
        return sysAreaMapper.findNameByParentCode(parentCode);
    }
}
